﻿using Magicodes.ExporterAndImporter.Core;
using Magicodes.ExporterAndImporter.Core.Models;
using Magicodes.ExporterAndImporter.Excel;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.IO;
using RayD.Core;
using System.Web;

namespace RayD.App.Magicodes
{
    /// <summary>
    /// Magicodes 报表通用封装
    /// </summary>
    public static class MagicodeReport
    {
        /// <summary>
        /// 导出Excel文件
        /// </summary>
        /// <typeparam name="T">导出Dto</typeparam>
        /// <param name="filename">导出文件名</param>
        /// <param name="source">数据源</param>
        /// <returns></returns>
        public static byte[] ExportExcel<T>(string filename, ICollection<T> source) where T : class, new()
        {
            //解决 Refused to get unsafe header "XXX"的错误
            HttpContextHelper.Instance.Response.Headers.Add("Access-Control-Expose-Headers", "filename");
            //文件名（Url加密防止中文乱码）
            HttpContextHelper.Instance.Response.Headers.Add("filename", HttpUtility.UrlEncode($"{filename}.xlsx"));
            //文件流导出
            IExporter exporter = new ExcelExporter();
            return exporter.ExportAsByteArray(source).Result;
        }

        /// <summary>
        /// 导出Excel导入模板
        /// </summary>
        /// <typeparam name="T">导出Dto</typeparam>
        /// <param name="filename">导出文件名</param>
        /// <returns></returns>
        public static byte[] ExportExcelTempl<T>(string filename) where T : class, new()
        {
            //解决 Refused to get unsafe header "XXX"的错误
            HttpContextHelper.Instance.Response.Headers.Add("Access-Control-Expose-Headers", "filename");
            //文件名（Url加密防止中文乱码）
            HttpContextHelper.Instance.Response.Headers.Add("filename", HttpUtility.UrlEncode($"{filename}.xlsx"));
            //文件流导出
            IImporter importer = new ExcelImporter();
            return importer.GenerateTemplateBytes<T>().Result;
        }

        /// <summary>
        /// 验证导入的Excel文件
        /// </summary>
        /// <typeparam name="T">导入Dto</typeparam>
        /// <param name="FullPath">Excel全路径</param>
        /// <param name="data">校验成功数据集（校验失败为null）</param>
        /// <param name="msg">导入消息</param>
        /// <param name="errorPath">错误标注文件路径</param>
        /// <returns></returns>
        public static bool ValidImportExcel<T>(string FullPath, out List<T> data, out string msg, out string errorPath) where T : class, new()
        {
            ExcelImporter importer = new ExcelImporter();
            var import = importer.Import<T>(FullPath).Result;
            //HasError为是否存在错误（不包含警告）
            if (!import.HasError)
            {
                data = import.Data.ToList();//校验成功数据集
                msg = "导入成功！";
                errorPath = "";//错误标注文件路径
                return true;
            }
            else
            {
                data = null;//校验成功数据集
                msg = "导入校验失败！";
                errorPath = "";//错误标注文件路径

                #region 错误分类
                //Exception导入异常信息
                if (import.Exception != null) { msg = import.Exception.Message; }
                //TemplateErrors为模板错误，比如必填列缺失等错误信息。支持错误等级（警告、错误）
                else if (import.TemplateErrors.Count > 0) { msg = "模板错误,请检查！"; }
                //RowErrors为验证错误，比如必填、重复验证、文本长度等等。会给出行号、字段以及字段错误集合
                else if (import.RowErrors.Count > 0)
                {
                    msg = $"导入校验失败！共计【{import.RowErrors.Sum(c => c.FieldErrors.Count)}】处错误";
                    errorPath = FullPath.Replace(Path.GetExtension(FullPath), "_" + Path.GetExtension(FullPath));
                }
                #endregion

                return false;
            }
        }
    }
}
